package com.ruoyi.squadweb.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.cache.LocalCache;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.squadweb.domain.SquadjsServiceList;
import com.ruoyi.squadweb.dto.*;
import com.ruoyi.squadweb.mapper.SquadjsServiceListMapper;
import com.ruoyi.squadweb.service.PlayerInfoService;
import com.ruoyi.squadweb.utils.PlayerResolverHttpUtils;
import com.ruoyi.squadweb.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: 1.0
 */

@Service
public class PlayerInfoServiceImpl implements PlayerInfoService {
    @Value("${squad.ipAddress}")
    private String url;

    @Autowired
    private LocalCache localCache;
    @Autowired
    private SquadjsServiceListMapper squadjsServiceListMapper;
    @Override
    public TableDataInfo getList(PlayerDTO playerDTO) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        String url = getURL(playerDTO.getServiceId());
        List<String> data = PlayerResolverHttpUtils.sendGet(url + "&cmd=ListPlayers", null, Constants.UTF8);
        if (data.size() <1) {
            throw new BaseException("暂时没有数据");
        }
        List<PlayerNewVO> playerNewVOS = PlayerResolverHttpUtils.playerResolver(data);
        System.out.println(playerNewVOS);
//        return null;
        List<PlayerNewVO> collect;
        if (!StringUtils.isEmpty(playerDTO.getName())) {
            collect = playerNewVOS.stream().filter(item -> {
                        if (!StringUtils.isEmpty(item.getName())) {
                            boolean contains = item.getName().contains(playerDTO.getName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getOnlineIds().get(1))) {
                            boolean contains = item.getOnlineIds().get(1).contains(playerDTO.getName());
                            if (contains) {
                                return contains;
                            }
                        }
                        return false;
                    })
                    .skip((long) (playerDTO.getPageNum() - 1) * playerDTO.getPageSize())
                    .limit(playerDTO.getPageSize())
                    .collect(Collectors.toList());
        } else {
            collect = playerNewVOS.stream().skip((long) (playerDTO.getPageNum() - 1) * playerDTO.getPageSize())
                    .limit(playerDTO.getPageSize())
//                    .peek(item -> squadVOS.forEach(squadVO -> {
//                        try {
//                            if (item.getSquadID().equals(squadVO.getSquadID())&&item.getTeamID().equals(squadVO.getTeamID())){
//                                item.setSquadVO(squadVO);
//                            }
//                        } catch (Exception ignored) {
//                        }
//
//                    }))
                    .collect(Collectors.toList());
        }
        //创建一个假的PlayerNewVO并赋值
        PlayerNewVO playerNewVO = new PlayerNewVO();
        playerNewVO.setName("测试");
        List<String> list = new ArrayList<>();
        list.add("1111");
        list.add("222");
        playerNewVO.setOnlineIds(list);
        playerNewVO.setLeader("true");
        collect.add(playerNewVO);
        playerNewVOS.add(playerNewVO);
        // 输出Java List对象
        tableDataInfo.setRows(collect);
        tableDataInfo.setTotal(playerNewVOS.size());
        return tableDataInfo;
    }


    /**
     * 获取小队信息
     * @return squadVOS
     */
    @Override
    public TableDataInfo getTeamList(SquadDTO squadDTO) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        String url = getURL(squadDTO.getServiceId());
        String data = HttpUtils.sendGet(url+"/rcon/get_squads");
        if (data.length() < 20) {
            throw new BaseException("暂时没有数据");
        }
        List<SquadVO> squadVOS = JSON.parseArray(data, SquadVO.class);
        List<SquadVO> collect;
        if (!StringUtils.isEmpty(squadDTO.getSquadName())) {
            collect = squadVOS.stream().filter(item -> {
                        if (!StringUtils.isEmpty(item.getSquadName())) {
                            boolean contains = item.getSquadName().contains(squadDTO.getSquadName());
                            if (contains) {
                                return contains;
                            }
                        }
                        return false;
                    })
                    .skip((long) (squadDTO.getPageNum() - 1) * squadDTO.getPageSize())
                    .limit(squadDTO.getPageSize())
                    .collect(Collectors.toList());
        } else {
            collect = squadVOS.stream().skip((long) (squadDTO.getPageNum() - 1) * squadDTO.getPageSize())
                    .limit(squadDTO.getPageSize())
                    .collect(Collectors.toList());
        }
        tableDataInfo.setRows(collect);
        tableDataInfo.setTotal(squadVOS.size());
        return tableDataInfo;
    }

    /**
     * 击杀信息
     * @return
     */
    @Override
    public TableDataInfo getKillList(KillDTO killDTO) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        String url = getURL(killDTO.getServiceId());
        String response = HttpUtils.sendGet(url+"/data/get_kill_record");
        if (response.length() < 20) {
            throw new BaseException("暂时没有数据");
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String data = jsonObject.get("data").toString();
        List<KillVO> killVOS = JSON.parseArray(data, KillVO.class);
        List<KillVO> collect;
        if (!StringUtils.isEmpty(killDTO.getAttackerName())) {
            collect = killVOS.stream().filter(item -> {
                        if (!StringUtils.isEmpty(item.getAttacker())) {
                            boolean contains = item.getAttacker().contains(killDTO.getAttackerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getAttackerName())) {
                            boolean contains = item.getAttackerName().contains(killDTO.getAttackerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getVictim())) {
                            boolean contains = item.getVictim().contains(killDTO.getAttackerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getVictimName())) {
                            boolean contains = item.getVictimName().contains(killDTO.getAttackerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        return false;
                    })
                    .skip((long) (killDTO.getPageNum() - 1) * killDTO.getPageSize())
                    .limit(killDTO.getPageSize())
                    .collect(Collectors.toList());
        } else {
            collect = killVOS.stream().skip((long) (killDTO.getPageNum() - 1) * killDTO.getPageSize())
                    .limit(killDTO.getPageSize())
                    .collect(Collectors.toList());
        }

        tableDataInfo.setRows(collect);
        tableDataInfo.setTotal(killVOS.size());
        return tableDataInfo;
    }

    /**
     * 聊天记录
     * @return
     */
    @Override
    public TableDataInfo getChatList(ChatDTO chatDTO) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        String url = getURL(chatDTO.getServiceId());
        String response = HttpUtils.sendGet(url+"/data/get_chat_record");
        if (response.length() < 20) {
            throw new BaseException("暂时没有数据");
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String data = jsonObject.get("data").toString();
        List<ChatVO> chatVOS = JSON.parseArray(data, ChatVO.class);
        List<ChatVO> collect;
        if (!StringUtils.isEmpty(chatDTO.getPlayerName())) {
            collect = chatVOS.stream().filter(item -> {
                        if (!StringUtils.isEmpty(item.getPlayerName())) {
                            boolean contains = item.getPlayerName().contains(chatDTO.getPlayerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getPlayerSteamID())) {
                            boolean contains = item.getPlayerSteamID().contains(chatDTO.getPlayerName());
                            if (contains) {
                                return contains;
                            }
                        }
                        return false;
                    })
                    .skip((long) (chatDTO.getPageNum() - 1) * chatDTO.getPageSize())
                    .limit(chatDTO.getPageSize())
                    .collect(Collectors.toList());
        } else {
            collect = chatVOS.stream().skip((long) (chatDTO.getPageNum() - 1) * chatDTO.getPageSize())
                    .limit(chatDTO.getPageSize())
                    .collect(Collectors.toList());
        }

        tableDataInfo.setRows(collect);
        tableDataInfo.setTotal(chatVOS.size());
        return tableDataInfo;
    }

    /**
     * 建队记录
     * @return
     */
    @Override
    public TableDataInfo getSquadCreatList(SquadCreateDTO squadCreateDTO) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        String url = getURL(squadCreateDTO.getServiceId());
        String response = HttpUtils.sendGet(url+"/data/get_squad_create_record");
        if (response.length() < 20) {
            throw new BaseException("暂时没有数据");
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String data = jsonObject.get("data").toString();
        List<SquadCreateVO> squadCreateVOS = JSON.parseArray(data, SquadCreateVO.class);
        List<SquadCreateVO> collect;
        if (!StringUtils.isEmpty(squadCreateDTO.getMasterName())) {
            collect = squadCreateVOS.stream().filter(item -> {
                        if (!StringUtils.isEmpty(item.getMasterName())) {
                            boolean contains = item.getMasterName().contains(squadCreateDTO.getMasterName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getMasterSteamID())) {
                            boolean contains = item.getMasterSteamID().contains(squadCreateDTO.getMasterName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getSquadID())) {
                            boolean contains = item.getSquadID().contains(squadCreateDTO.getMasterName());
                            if (contains) {
                                return contains;
                            }
                        }
                        if (!StringUtils.isEmpty(item.getSquadName())) {
                            boolean contains = item.getSquadName().contains(squadCreateDTO.getMasterName());
                            if (contains) {
                                return contains;
                            }
                        }
                        return false;
                    })
                    .skip((long) (squadCreateDTO.getPageNum() - 1) * squadCreateDTO.getPageSize())
                    .limit(squadCreateDTO.getPageSize())
                    .collect(Collectors.toList());
        } else {
            collect = squadCreateVOS.stream().skip((long) (squadCreateDTO.getPageNum() - 1) * squadCreateDTO.getPageSize())
                    .limit(squadCreateDTO.getPageSize())
                    .collect(Collectors.toList());
        }

        tableDataInfo.setRows(collect);
        tableDataInfo.setTotal(squadCreateVOS.size());
        return tableDataInfo;
    }

    public Map<String, String> urlHead() {
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Authorization", getToken());
        return headMap;
    }

    private String getToken() {
        return localCache.getPersistentCache("squadToken");
    }
    private String getURL(String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            throw new BaseException("服务器不存在，请输入正确服务器");
        }
        SquadjsServiceList squadjsServiceList = squadjsServiceListMapper.selectSquadjsServiceListById(Long.parseLong(serviceId));
        if (squadjsServiceList == null || StringUtils.isEmpty(squadjsServiceList.getIp())) {
            throw new BaseException("服务器不存在，请输入正确服务器");
        }
        return "http://api.bctc-squad.cn:8088/api/Rcon.sh?ip="+squadjsServiceList.getIp()+"&port="+squadjsServiceList.getPort()+"&passwd="+squadjsServiceList.getPassword();
    }

}
